const path = require('path')
const router = require('koa-router')()
const Sequelize = require('sequelize')
const fileModel = require('../../models/file')
const jwt = require('jsonwebtoken')
const bodyParser = require('koa-bodyparser')

const dao = require('../../dao/' + path.basename(__dirname))

router.post('/', async (ctx, next) => {
    try {

        await bodyParser()

        /*

        // 生成hash
        const fsHash = crypto.createHash('md5')
        const buffer = fs.readFileSync(file.path)
        fsHash.update(buffer);
        const fileHash = fsHash.digest('hex')
        // console.log('文件的MD5是：%s', fileHash)

         */

        // 解析jwt
        const decode = await jwt.verify(ctx.request.body.fields.auth, jwtPassword)
        const postParams = ctx.request.body
        const file = postParams.files.file; // 获取上传文件
        //const file = decode.files.file; // 获取上传文件

        // 判别重复, 哈希重复时不再上传
        const findFile = await fileModel.findOne({
            where: {
                hash: file.hash,
            }
        })

        if(findFile.length !== 0) {
            console.log('A same Hash File Has been Uploaded !')
            return ctx.body = {
                message: 'A same Hash File Has been Uploaded !\n',
                hash : ctx.query.hash
            }
        }

        // 路由响应
        ctx.status = 200
        ctx.body = {
            message: 'No Same-Hash File !\n',
            hash : ctx.query.hash
        }

    }
    catch (err) {
        ctx.status = 500
        ctx.body = {
            message: err.message
        }
        // await next()
    }
})


module.exports = router.routes();